package org.jeecgframework.tinydao.spring.rowMapper;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.jeecgframework.tinydao.util.CamelCaseUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;

public class GenericRowMapper<T> implements RowMapper<T> {

	private Class<T> clazz;
	
	public GenericRowMapper(Class<T> clazz) {
		super();
		this.clazz = clazz;
	}

	@Override
	public T mapRow(ResultSet rs, int rowNum) throws SQLException {
		
		 try {
			 ResultSetMetaData rsmd = rs.getMetaData();
			 int columnCount = rsmd.getColumnCount();
			T bean = clazz.newInstance();
			ConvertUtils.register(new org.jeecgframework.tinydao.util.DateConverter() , Date.class);
			ConvertUtils.register(new org.jeecgframework.tinydao.util.BigDecimalConverter() , BigDecimal.class);
			ConvertUtils.register(new org.jeecgframework.tinydao.util.IntegerConverter() , Integer.class);
			for(int i= 1;i<columnCount;i++){
				String key= getColumnKey(JdbcUtils.lookupColumnName(rsmd, i));
				Object obj = getColumnValue(rs,i);
				String camelKey = CamelCaseUtils.toCamelCase(key);
				BeanUtils.setProperty(bean, camelKey, obj);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private Object getColumnValue(ResultSet rs, int i) throws SQLException {
	 
		return JdbcUtils.getResultSetValue(rs, i);
	}

	private String getColumnKey(String lookupColumnName) {
		return lookupColumnName;
	}

}
